Imports System.Collections.Generic

Partial Class Budget_Budget
    Inherits System.Web.UI.Page

    Private blError As Boolean
    Private intKey As Integer

    Private Const COLUMN_DELETE As Integer = 5
    Private Const COLUMN_UPDATE As Integer = 4

    Private Const NEWVALUES_EFFECTIVEDATE As Integer = 0
    Private Const NEWVALUES_EXPIRATIONDATE As Integer = 1
    Private Const NEWVALUES_AMOUNT As Integer = 2


    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        ErrorSummary.Visible = False
        SetupJavaScript()

        If Not IsPostBack Then
            UserAuthorization.CheckPagePermission(Cdm.DataCore.UserSecurity.Permission.PermissionType.CaseBudget, "VIEW")

        End If
        Dim Participant As New Cdm.DataCore.Entities.Participant()
        Participant = EntityController.GetParticipant()
        EntityController.SetSubNavTabsFinancial(Me.EditCaseSubNav2)
        EntityController.SetFinancialTab(Me.FinancialSubName, Me.EditCaseSubNav2)
        If Participant Is Nothing Then
            ParticipantName2.Text = "There is no participant associated with this user."
        Else
            Session("ParticipantId") = Participant.Id
            If Not UserAuthorization.HasInsertPermission(Cdm.DataCore.UserSecurity.Permission.PermissionType.CaseBudget) Then
                AddBudgetButton.Visible = False
            End If
            If Not UserAuthorization.HasDeletePermssion(Cdm.DataCore.UserSecurity.Permission.PermissionType.CaseBudget) Then
                BudgetGridView.Columns(COLUMN_DELETE).Visible = False
            End If
            If Not UserAuthorization.HasUpdatePermission(Cdm.DataCore.UserSecurity.Permission.PermissionType.CaseBudget) Then
                BudgetGridView.Columns(COLUMN_UPDATE).Visible = False
            End If
            ParticipantName.Text = Participant.DisplayLastNameFirst()
            ParticipantName2.Text = "There is no " + EntityController.ReplaceDisplayName("Spending Plan") + " for " + Participant.DisplayLastNameFirst()
        End If
    End Sub

    Private Sub SetupJavaScript()
        EntityController.JavaScriptSetFixedHeight(30)
        EntityController.JavaScriptAddChildDiv(Me.maindiv.ClientID, 100)
        EntityController.JavaScriptAddChildDiv(Me.gridViewDiv.ClientID, 140)
    End Sub

    Protected Sub AddBudgetButton_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles AddBudgetButton.Click
        AddBudgetButton.Visible = False
        BudgetGridView.Visible = False

        SubmitButton.Text = "Insert"
        SubmitButton.Attributes.Add("onclick", "return confirm('Please verify: are you sure this amount is correct?');")
        SubmitButton.Visible = True
        CancelButton.Visible = True
        'lblRequired.Visible = True
        Dim ddlBudgetPeriod As DropDownList = CType(BudgetFormView.FindControl("ddlBudgetPeriodInsert"), DropDownList)
        If ddlBudgetPeriod IsNot Nothing Then
            ddlBudgetPeriod.DataSource = Cdm.DataCore.LookupTables.LuBudgetPeriod.ListAll()
            ddlBudgetPeriod.DataTextField = "Description"
            ddlBudgetPeriod.DataValueField = "BudgetPeriodId"
            ddlBudgetPeriod.DataBind()
            Try
                'Set the default budget period from the application setting
                Dim defaultBudgetPeriod = CStr(Application("DefaultBudgetPeriod")).ToUpper()
                For i As Integer = 0 To ddlBudgetPeriod.Items.Count - 1
                    If ddlBudgetPeriod.Items(i).Text.ToUpper().Equals(defaultBudgetPeriod) Then
                        ddlBudgetPeriod.SelectedIndex = i
                    End If
                Next
            Catch ex As Exception
                'Don't Set a default
            End Try
        End If

        Me.BudgetFormView.ChangeMode(FormViewMode.Insert)
        Me.BudgetFormView.Visible = True
    End Sub

    Protected Sub SubmitButton_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles SubmitButton.Click
        Dim Participant As New Cdm.DataCore.Entities.Participant()
        Participant = EntityController.GetParticipant()
        If SubmitButton.Text = "Insert" Then
            Dim Budget As New Cdm.DataCore.Budget.Budget

            Dim txtEffectiveDate As InputControls.GenericInputControl = CType(BudgetFormView.FindControl("txtEffectiveDateInsert"), InputControls.GenericInputControl)
            Dim txtExpirationDate As InputControls.GenericInputControl = CType(BudgetFormView.FindControl("txtExpirationDateInsert"), InputControls.GenericInputControl)
            Dim ddlBudgetPeriod As DropDownList = CType(BudgetFormView.FindControl("ddlBudgetPeriodInsert"), DropDownList)
            Dim txtBudgetAmount As TextBox = CType(BudgetFormView.FindControl("txtBudgetAmountInsert"), TextBox)

            If (txtEffectiveDate.Value = "") Or (txtBudgetAmount.Text = "") Then
                formError("Fields marked with an asterisk need to be filled in.")
                Exit Sub
            End If


            Budget.ParticipantId = Participant.ParticipantId
            Try
                Budget.EffectiveDate = txtEffectiveDate.Value
                Budget.ExpirationDate = txtExpirationDate.Value
                Budget.BudgetPeriodId = ddlBudgetPeriod.SelectedValue
                Budget.BudgetAmount = txtBudgetAmount.Text
                Budget.DateModified = Now
                Budget.LastModified = UserAuthorization.CurrentUser.LogonId
                'Budget.SetExpirationDates(Budget.ParticipantId, Budget.EffectiveDate.Subtract(System.TimeSpan.FromDays(1)))
                Budget.Persist()
                If Not String.IsNullOrEmpty(Budget.ErrorMessage) Then
                    If Budget.ErrorMessage.Equals("This budget has a spending plan tied to it whose dates are outside the date range of the budget.") Then
                        Session("EditBudget") = "Budget"
                        Response.Redirect("BudgetEditDates.aspx")
                    Else
                        formError(Budget.ErrorMessage)
                    End If

                    Exit Sub
                End If
            Catch ex As Exception
                formError(ex.Message)
                Exit Sub
            End Try

        ElseIf SubmitButton.Text = "Update" Then
            Dim key As DataKey = BudgetFormView.DataKey
            Dim Budget As Cdm.DataCore.Budget.Budget

           

            intKey = key.Value
            Budget = Cdm.DataCore.Budget.Budget.Retrieve(intKey)

            Dim txtEffectiveDate As InputControls.GenericInputControl = CType(BudgetFormView.FindControl("txtEffectiveDateEdit"), InputControls.GenericInputControl)
            Dim txtBudgetAmount As TextBox = CType(BudgetFormView.FindControl("txtBudgetAmountEdit"), TextBox)

            If (txtEffectiveDate.Value = "") Or (txtBudgetAmount.Text = "") Then
                formError("Fields marked with an asteric need to be filled in.")
                Exit Sub
            End If

            Try
                Budget.BudgetId = intKey
                Budget.EffectiveDate = txtEffectiveDate.Value
                Budget.BudgetAmount = txtBudgetAmount.Text
                Budget.DateModified = Now
                Budget.LastModified = UserAuthorization.CurrentUser.LogonId
                'Budget.SetExpirationDates(Budget.ParticipantId, Budget.EffectiveDate.Subtract(System.TimeSpan.FromDays(1)))
                Budget.Persist()
                If Not String.IsNullOrEmpty(Budget.ErrorMessage) Then
                    formError(Budget.ErrorMessage)
                    Exit Sub
                End If
            Catch ex As Exception
                formError(ex.Message)
                Exit Sub
            End Try

        End If

        If Not Participant Is Nothing Then
            EntityController.SendNotification(Cdm.DataCore.CaseNotes.Notification.NotificationType.BudgetAmountisEntered, Participant.ParticipantId)
        End If

        SubmitButton.Visible = False
        CancelButton.Visible = False
        BudgetFormView.Visible = False
        'lblRequired.Visible = False

        ErrorSummary.Visible = False

        Me.BudgetObjectDataSource.Select()
        BudgetGridView.DataBind()
        AddBudgetButton.Visible = True
        BudgetGridView.Visible = True

    End Sub

    Protected Sub formError(ByVal strError As String)
        Me.ErrorSummary.SetSingleError(strError)
        ErrorSummary.Visible = True
    End Sub

    Protected Sub BudgetGridView_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles BudgetGridView.RowCommand
        Try
            If e.CommandName.Equals("Remove") Then
                Try
                    Dim budgetid As Integer = CInt(e.CommandArgument)
                    Dim deleteBudget As Cdm.DataCore.Budget.Budget = Cdm.DataCore.Budget.Budget.Retrieve(budgetid)

                    Dim deleteSpendingPlans As List(Of Cdm.DataCore.Budget.SpendingPlan) = Cdm.DataCore.Budget.SpendingPlan.ListByBudgetId(budgetid)
                    Dim isAutoBudget As Boolean = False

                    If Application("SpendingPlanDownloadWithoutBudget").ToString().ToLower().Equals("true") Then
                        isAutoBudget = True
                    End If

                    'If there is no associated spending plan, go ahead with the delete.
                    If deleteSpendingPlans Is Nothing OrElse deleteSpendingPlans.Count = 0 Then
                        deleteBudget.Remove()
                    
                        Me.BudgetObjectDataSource.Select()
                        BudgetGridView.DataBind()
                        'If there is an associated spending plan, and the application setting is false, then
                        'do not allow the delete - show an error message
                    ElseIf HasSpending(deleteSpendingPlans) Then
                        Dim deleteSpendingPlan As Cdm.DataCore.Budget.SpendingPlan = deleteSpendingPlans(deleteSpendingPlans.Count - 1)
                        formError("Can not delete Budget.  It is associated with a spending plan, and expenditures have been reported against it.")
                    ElseIf isAutoBudget = False Then
                        Dim deleteSpendingPlan As Cdm.DataCore.Budget.SpendingPlan = deleteSpendingPlans(deleteSpendingPlans.Count - 1)
                        formError(String.Format("Can not delete budget.  Budget is already associated with {0} spending plan(s); the latest has effective dates {1} - {2}. " + _
                        deleteSpendingPlans.Count.ToString(), deleteSpendingPlan.StartDate.ToShortDateString(), deleteSpendingPlan.EndDate.ToShortDateString()))
                    Else
                        'if there is a spending plan, and the app setting is true, then
                        'show a confirmation message where user can confirm or cancel.
                        Dim deleteSpendingPlan As Cdm.DataCore.Budget.SpendingPlan = deleteSpendingPlans(deleteSpendingPlans.Count - 1)
                        formError(String.Format("Budget is already associated with {0} spending plan(s), with effective dates {1} - {2}. " + _
                                "Deleting this budget will also delete all associated spending plans.  Do you wish to continue?", _
                                deleteSpendingPlans.Count.ToString(), deleteSpendingPlan.StartDate.ToShortDateString(), deleteSpendingPlan.EndDate.ToShortDateString()))
                        Me.ConfirmDeleteButton.CommandArgument = budgetid.ToString()
                        ShowConfirmButtons(True)
                    End If
                Catch ex As Exception
                    formError("Can not delete budget.  It is already associated with a spending plan.")
                End Try
            End If
        Catch Ex As Exception
            formError(Ex.Message)
        End Try

        ''If e.CommandName.Equals("Edit") Then
        'Dim budgetid As Integer = CInt(e.CommandArgument)
        'Dim editBudget As Cdm.DataCore.Budget.Budget = Cdm.DataCore.Budget.Budget.Retrieve(budgetid)
        'End If

    End Sub

    Private Function HasSpending(ByVal spendingPlans As List(Of Cdm.DataCore.Budget.SpendingPlan)) As Boolean
        Dim expenditureItems As List(Of Cdm.DataCore.Budget.ExpenditureReportItem)
        Dim spendingPlanId As Integer
        For i As Integer = 0 To spendingPlans.Count - 1
            spendingPlanId = spendingPlans(i).SpendingPlanId
            expenditureItems = Cdm.DataCore.Budget.ExpenditureReportItem.ListBySpendingPlan(spendingPlanId)
            If Not expenditureItems Is Nothing Then
                If expenditureItems.Count > 0 Then
                    Return True
                End If
            End If
        Next
        Return False
    End Function

    Protected Sub BudgetGridView_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles BudgetGridView.RowDataBound

        If e.Row.RowIndex = 0 Then
            AccessibilityController.AddImageToSortableGridHeaders(BudgetGridView)
        End If

        Dim buttonControl As Button
        Dim budgetPeriodDropDown As DropDownList
        Dim boundBudget As Cdm.DataCore.Budget.Budget
        buttonControl = e.Row.FindControl("DeleteButton")
        If buttonControl IsNot Nothing Then
            boundBudget = e.Row.DataItem
            buttonControl.Attributes.Add("onclick", "return confirm('Are you sure you want to delete this budget?');")
            buttonControl.CommandArgument = boundBudget.BudgetId.ToString()
        End If

        budgetPeriodDropDown = e.Row.FindControl("BudgetPeriodDropDownList")
        If budgetPeriodDropDown IsNot Nothing Then
            budgetPeriodDropDown.DataSource = Cdm.DataCore.LookupTables.LuBudgetPeriod.ListAll()
            budgetPeriodDropDown.DataTextField = "Description"
            budgetPeriodDropDown.DataValueField = "BudgetPeriodId"
            budgetPeriodDropDown.DataBind()
            boundBudget = e.Row.DataItem
            budgetPeriodDropDown.SelectedValue = boundBudget.BudgetPeriodId.ToString()
        End If

    End Sub

    Protected Sub BudgetGridView_RowUpdated(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewUpdatedEventArgs) Handles BudgetGridView.RowUpdated
        Try
            Dim returnMessage As String
            returnMessage = "Hello"
        Catch ex As Exception

        End Try

    End Sub

    Protected Sub BudgetGridView_RowUpdating(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewUpdateEventArgs) Handles BudgetGridView.RowUpdating
        Dim bCancel As Boolean = False
        Dim errorMessage As String = ""

        Dim Participant As New Cdm.DataCore.Entities.Participant()
        Participant = EntityController.GetParticipant()
        If Not IsDate(e.NewValues(NEWVALUES_EFFECTIVEDATE)) Then
            bCancel = True
            errorMessage = "Please enter a valid date for effective date."
        End If
        If e.NewValues(NEWVALUES_EXPIRATIONDATE) IsNot Nothing Then
            If Not IsDate(e.NewValues(NEWVALUES_EXPIRATIONDATE)) And Not (e.NewValues(NEWVALUES_EXPIRATIONDATE).ToString.Equals("")) Then
                bCancel = True
                errorMessage = "Please enter a valid expiration date, or leave blank if there is no expiration date."
            End If
        End If
        If Not IsNumeric(e.NewValues(NEWVALUES_AMOUNT)) Then
            bCancel = True
            errorMessage = "Please enter a valid budget amount."
        End If

        If bCancel Then
            e.Cancel = True
            ErrorSummary.SetSingleError(errorMessage)
            ErrorSummary.Visible = True
        Else
            ErrorSummary.Visible = False
        End If

        e.NewValues.Add("ParticipantId", Participant.ParticipantId)
        Dim budgetPeriodDropDown As DropDownList = Me.BudgetGridView.Rows(e.RowIndex).FindControl("BudgetPeriodDropDownList")
        If budgetPeriodDropDown IsNot Nothing Then
            e.NewValues.Add("BudgetPeriodId", budgetPeriodDropDown.SelectedValue)
        End If
        e.NewValues.Add("LastModified", UserAuthorization.CurrentUser.LogonId)
        e.NewValues.Add("DateModified", DateTime.Now)
        EntityController.SendNotification(Cdm.DataCore.CaseNotes.Notification.NotificationType.BudgetAmountisEntered, Participant.ParticipantId)
        'If (e.NewValues("EffectiveDate") = "") Or (e.NewValues("ExpirationDate") = "") Or (e.NewValues("PlanType") = "") Or (e.NewValues("BudgetAmount") = "") Then
        '    formError("Fields marked with an asteric need to be filled in.")
        '    Exit Sub
        'End If

        SaveBudget(e)

    End Sub

    Private Sub SaveBudget(ByVal e As System.Web.UI.WebControls.GridViewUpdateEventArgs)
        Dim updateBudget As Cdm.DataCore.Budget.Budget
        Dim budgetId As Integer = CInt(BudgetGridView.DataKeys(e.RowIndex)(0))
        If budgetId > 0 Then
            updateBudget = Cdm.DataCore.Budget.Budget.Retrieve(budgetId)
        Else
            updateBudget = New Cdm.DataCore.Budget.Budget()
        End If

        Dim validateErrors As ArrayList = ValidateData(e)
        If validateErrors.Count > 0 Then
            Me.ErrorSummary.SetErrors(validateErrors)
            Me.ErrorSummary.Visible = True
            Exit Sub
        End If
        
        updateBudget.BudgetAmount = Convert.ToDouble(e.NewValues(NEWVALUES_AMOUNT))
        updateBudget.BudgetPeriodId = e.NewValues().Item("BudgetPeriodId")
        updateBudget.DateModified = DateTime.Now
        updateBudget.EffectiveDate = Convert.ToDateTime(e.NewValues(NEWVALUES_EFFECTIVEDATE))
        updateBudget.ExpirationDate = Convert.ToDateTime(e.NewValues(NEWVALUES_EXPIRATIONDATE))
        updateBudget.LastModified = UserAuthorization.CurrentUser.LogonId
        updateBudget.ParticipantId = e.NewValues().Item("ParticipantId")
        updateBudget.Persist()

        If Not String.IsNullOrEmpty(updateBudget.ErrorMessage) Then
            If updateBudget.ErrorMessage.Equals("This budget has a spending plan tied to it whose dates are outside the date range of the budget.") Then
                Session("EditBudget") = updateBudget
                Response.Redirect("BudgetEditDates.aspx")
            Else
                formError(updateBudget.ErrorMessage)
            End If
        End If

    End Sub
    ''' <summary>
    ''' Checks if data entered is valid.
    '''   Checks if 1: Budget amount is entered and numeric
    '''             2: Start Date and End Date are entered, and valid dates.
    '''             3: End Date is not before Start Date
    ''' </summary>
    ''' <param name="e"></param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Function ValidateData(ByVal e As System.Web.UI.WebControls.GridViewUpdateEventArgs) as ArrayList
        Dim validateErrors As New ArrayList
        If Not IsNumeric(e.NewValues(NEWVALUES_AMOUNT)) Then
            validateErrors.Add("Please enter a valid budget amount.")
        End If

        If Not IsDate(e.NewValues(NEWVALUES_EFFECTIVEDATE)) Then
            validateErrors.Add("Entered start date is not a valid date.")
        End If

        If Not IsDate(e.NewValues(NEWVALUES_EXPIRATIONDATE)) Then
            validateErrors.Add("Entered end date is not a valid date.")
        End If

        If IsDate(e.NewValues(NEWVALUES_EXPIRATIONDATE)) And _
            IsDate(e.NewValues(NEWVALUES_EFFECTIVEDATE)) Then
            Dim startDate As DateTime = CDate(e.NewValues(NEWVALUES_EFFECTIVEDATE))
            Dim endDate As DateTime = CDate(e.NewValues(NEWVALUES_EXPIRATIONDATE))
            If endDate < startDate Then
                validateErrors.Add("End date may not be before the start date.")
            End If
        End If

        Return validateErrors
    End Function

    Protected Sub EditCaseSubNav2_ChangeMenu(ByVal sender As Object, ByVal e As System.EventArgs) Handles EditCaseSubNav2.ChangeMenu
        EntityController.ReturnToCasePersonalPage(EditCaseSubNav2)
    End Sub

    Protected Sub CancelButton_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles CancelButton.Click
        AddBudgetButton.Visible = True
        BudgetGridView.Visible = True

        SubmitButton.Visible = False
        CancelButton.Visible = False
        'lblRequired.Visible = False

        'Me.BudgetFormView.ChangeMode(FormViewMode.Insert)
        Me.BudgetFormView.Visible = False
    End Sub

    Protected Sub BudgetFormView_ItemInserted(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.FormViewInsertedEventArgs) Handles BudgetFormView.ItemInserted

    End Sub

    Protected Sub BudgetFormView_ItemInserting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.FormViewInsertEventArgs) Handles BudgetFormView.ItemInserting
        Dim insertBudget As New Cdm.DataCore.Budget.Budget
        insertBudget.ParticipantId = EntityController.GetParticipant().ParticipantId
        insertBudget.BudgetAmount = e.Values(0)
        insertBudget.Persist()
    End Sub

    Protected Sub BudgetFormView_ModeChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles BudgetFormView.ModeChanged
        If BudgetFormView.FindControl("ddlBudgetPeriodInsert") IsNot Nothing Then
            Dim insertPeriodDropDownList As DropDownList = BudgetFormView.FindControl("ddlBudgetPeriodInsert")
            If insertPeriodDropDownList IsNot Nothing Then
                insertPeriodDropDownList.DataSource = Cdm.DataCore.LookupTables.LuBudgetPeriod.ListAll()
                insertPeriodDropDownList.DataTextField = "Description"
                insertPeriodDropDownList.DataValueField = "BudgetPeriodId"
                insertPeriodDropDownList.DataBind()
            End If

        End If
    End Sub

    Protected Sub BudgetFormView_ModeChanging(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.FormViewModeEventArgs) Handles BudgetFormView.ModeChanging
        Dim insertPeriodDropDownList As InputControls.GenericInputControl = BudgetFormView.FindControl("ddlBudgetPeriodInsert")
        If insertPeriodDropDownList IsNot Nothing Then
            insertPeriodDropDownList.DataSource = Cdm.DataCore.LookupTables.LuBudgetPeriod.ListAll()
            insertPeriodDropDownList.DataBind()
        End If

    End Sub

    Protected Sub CancelDeleteButton_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles CancelDeleteButton.Click
        ShowConfirmButtons(False)
    End Sub

    Protected Sub ConfirmDeleteButton_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles ConfirmDeleteButton.Click
        Try
            Dim budgetid As Integer = CInt(ConfirmDeleteButton.CommandArgument)
            Dim deleteBudget As Cdm.DataCore.Budget.Budget = Cdm.DataCore.Budget.Budget.Retrieve(budgetid)
            deleteBudget.Remove()
            ShowConfirmButtons(False)
            Me.BudgetObjectDataSource.Select()
            BudgetGridView.DataBind()
        Catch ex As Exception

        End Try
    End Sub

    Private Sub ShowConfirmButtons(ByVal bShow As Boolean)
        ConfirmPanel.Visible = bShow
        BudgetGridView.Visible = Not bShow
        AddBudgetButton.Visible = Not bShow
    End Sub
End Class
